<template>
  <div class="order-container">
    <!-- 订单状态导航 -->
    <div class="status-tabs">
      <div
          class="tab-item"
          :class="{ active: panduan === '全部' }"
          @click="queryAll"
      >
        全部订单
      </div>
      <div
          class="tab-item"
          :class="{ active: panduan === '待接单' }"
          @click="doListAll"
      >
        待接单
      </div>
      <div
          class="tab-item"
          :class="{ active: panduan === '待配送' }"
          @click="daipeisong"
      >
        待配送
      </div>
    </div>

    <!-- 订单表格 -->
    <div class="card">
      <el-table
          :data="dingdanList"
          style="width: 100%;"
          class="order-table"
          stripe
      >
        <el-table-column prop="ddid" label="订单ID" width="100"></el-table-column>
        <el-table-column prop="ddzt" label="订单状态" width="120">
          <template #default="scope">
            <el-tag :type="getOrderStatusType(scope.row.ddzt)">
              {{ scope.row.ddzt }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="yhid" label="用户ID" width="100"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="120"></el-table-column>
        <el-table-column prop="dddz" label="地址" show-overflow-tooltip></el-table-column>
        <el-table-column prop="ddsj" label="下单时间" width="160"></el-table-column>
        <el-table-column prop="tprice" label="总价" width="100">
          <template #default="scope">
            <span class="price-text">¥{{ scope.row.tprice }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button
                  type="primary"
                  link
                  size="small"
                  @click="showDetailDialog(scope.row)"
                  class="action-btn"
              >
                详情
              </el-button>

              <div v-if="panduan === '待接单'">
                <el-button
                    type="success"
                    size="small"
                    @click="accept(scope.row)"
                    class="action-btn"
                >
                  接单
                </el-button>
                <el-button
                    type="danger"
                    size="small"
                    @click="doDelete(scope.row)"
                    class="action-btn"
                >
                  拒单
                </el-button>
              </div>

              <div v-else-if="panduan === '待配送'">
                <el-button
                    type="primary"
                    size="small"
                    @click="gofood(scope.row)"
                    class="action-btn"
                >
                  出餐
                </el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!-- 订单详情弹窗 -->
  <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="60%"
      top="10vh"
      class="order-dialog"
      destroy-on-close
  >
    <show-d-d-x-q
        ref="detailPageRef"
        @flushPage="reset"
        @closeDialog="detailDialogVisible = false">
    </show-d-d-x-q>
  </el-dialog>

  <!-- 新增订单弹窗 -->
  <el-dialog
      v-model="addDialogVisible"
      title="新增订单"
      width="40%"
      top="2vh"
      class="order-dialog"
      destroy-on-close
  >
    <add-dingdan
        @flushPage="reset"
        @closeDialog="addDialogVisible = false">
    </add-dingdan>
  </el-dialog>
</template>

<script setup>
import { nextTick, onMounted, reactive, ref } from 'vue'
import axios from "axios";
import { ElMessage } from "element-plus";
import ShowDDXQ from "../ddxiangqing/ShowDDXQ.vue";

const panduan = ref('');
const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')))
const dingdan = reactive({
  ddid: '',
  psks: '',
  yhid: '',
})

onMounted(() => {
  isUserQuery.value = false;
  queryAll();
});

const queryAll = async () => {
  panduan.value = '全部'
  const { data } = await axios.get(`/api/dingdan/all/${userInfo.value.sjid}`)
  if (data.code === 200) {
    dingdanList.value = [];
    dingdanList.value = data.data;
    ElMessage.success('查询成功');
  }
}

const doListAll = async () => {
  panduan.value = '待接单'
  dingdanList.value = [];
  const { data } = await axios.get(`/api/dingdan/dd/${userInfo.value.sjid}`)
  if (data.code === 200) {
    dingdanList.value = data.data;
    await showList();
  } else {
    ElMessage.error(data.message);
  }
}

const daipeisong = async () => {
  panduan.value = '待配送'
  const { data } = await axios.get(`/api/dingdan/daipeisong/${userInfo.value.sjid}`)
  if (data.code === 200) {
    dingdanList.value = [];
    dingdanList.value = data.data;
    ElMessage.success('查询成功');
  }
}

const peisong = ref({
  ddid: '',
  pszt: ''
})

const gofood = async (row) => {
  peisong.value.pszt = 3
  peisong.value.ddid = row.ddid;
  const { data } = await axios.put('/api/peisong/pszt', peisong.value)
  if (data.code === 200) {
    ElMessage.success('出餐成功');
    await daipeisong();
  }
}

const psdd = ref({
  ddid: ''
})

const dingdanList = ref();  // 订单信息列表
// 标记是否为用户主动查询（初始为 false）
const isUserQuery = ref(false);

const doList = async () => {
  dingdanList.value = [];
  const url = dingdan.ddid ? `/api/dingdan/${dingdan.ddid}` : '/api/dingdan';
  const { data } = await axios.get(url)
  console.log("订单信息列表", data);
  if (data.code === 200) {
    console.log(dingdan.ddid)
    dingdanList.value = dingdan.ddid
        ? [data.data]
        : data.data;
    // 只有用户主动查询时才显示成功提示
    if (isUserQuery.value) {
      /*ElMessage.success('查询成功');*/
      await showList();
    }
  } else {
    // 错误提示始终显示（无论是否用户操作）
    ElMessage.error(data.message);
  }
}

const showList = async () => {
  // 先确保订单数据已加载
  if (!dingdanList.value || dingdanList.value.length === 0) return;

  // 收集所有订单中的用户ID，去重
  const yhids = (dingdanList.value.map(order => order.yhid));

  if (yhids.length === 0) return;

  try {
    // 调用后端批量查询用户的接口
    const { data } = await axios.post('/api/dingdan/users', yhids);

    if (data.code === 200) {
      // 构建用户ID到用户信息的映射表
      const userMap = data.data.reduce((map, user) => {
        map[user.yhid] = user;
        return map;
      }, {});

      // 将用户信息关联到对应的订单
      dingdanList.value.forEach(order => {
        if (userMap[order.yhid]) {
          order.userInfo = userMap[order.yhid];
        }
      });
      if (isUserQuery.value) {
        ElMessage.success('用户信息加载成功');
      }
    } else {
      ElMessage.error(data.message);
    }
  } catch (error) {
    ElMessage.error('加载用户信息失败');
    console.error(error);
  }
}

const reset = async () => {
  dingdan.ddid = '';
  isUserQuery.value = true; // 标记为用户操作
  await doList();
  showList();
}

// 查询按钮点击：用户主动操作，需要显示提示
const handleQuery = async () => {
  isUserQuery.value = true; // 标记为用户操作
  await doList();
  // showList();
}

const addDialogVisible = ref(false)
const showAddDialog = () => {
  addDialogVisible.value = true;
}

const accept = async (row) => {
  psdd.value.ddid = row.ddid;
  const { data } = await axios.post('/api/peisong', psdd.value)
  console.log(data)
  if (data.code === 200) {
    ElMessage.success('接单成功');
    await doListAll()
  }
}

const detailDialogVisible = ref(false)
const detailPageRef = ref();
const showDetailDialog = (row) => {
  detailDialogVisible.value = true;
  nextTick(() => {
    console.log("2222", row);
    detailPageRef.value.handleShowData(row);
    console.log("1111", row);
  })
}

const doDelete = async (row) => {
  const { data } = await axios.delete(`/api/dingdan/${row.ddid}`)
  console.log(data);
  if (data.code === 200) {
    ElMessage.success('删除成功');
    // 删除后刷新列表，属于用户操作，显示提示
    isUserQuery.value = true;
    await doList();
    showList();
  } else {
    ElMessage.error(data.message);
  }
}

// 获取订单状态标签类型
const getOrderStatusType = (status) => {
  const statusMap = {
    '待接单': 'warning',
    '待配送': 'primary',
    '已完成': 'success',
    '已取消': 'danger'
  };
  return statusMap[status] || 'info';
}

const shortcuts = [
  {
    text: 'Last week',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setDate(start.getDate() - 7)
      return [start, end]
    },
  },
  {
    text: 'Last month',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 1)
      return [start, end]
    },
  },
  {
    text: 'Last 3 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 3)
      return [start, end]
    },
  },
]
</script>

<style scoped>
.order-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.status-tabs {
  display: flex;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  overflow: hidden;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 16px 0;
  font-size: 1rem;
  font-weight: 500;
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 3px solid transparent;
}

.tab-item:hover {
  background-color: #f9f9f9;
  color: #333;
}

.tab-item.active {
  color: #f58147;
  border-bottom: 3px solid #f58147;
  background-color: #fff9f2;
}

.card {
  background-color: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.order-table {
  border-radius: 8px;
  overflow: hidden;
}

.order-table :deep(.el-table__header th) {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}

.price-text {
  font-weight: 600;
  color: #f58147;
  font-size: 1.1rem;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.action-btn {
  margin: 0;
}

.order-dialog :deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

.order-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #f58147 0%, #ff6b35 100%);
  color: white;
  padding: 20px;
}

.order-dialog :deep(.el-dialog__title) {
  color: white;
  font-weight: 600;
}

.order-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .order-container {
    padding: 15px;
  }

  .status-tabs {
    flex-direction: column;
  }

  .tab-item {
    border-bottom: 1px solid #eee;
    border-left: 3px solid transparent;
  }

  .tab-item.active {
    border-bottom: 1px solid #eee;
    border-left: 3px solid #f58147;
  }

  .action-buttons {
    flex-direction: column;
  }

  .order-table :deep(.el-table__body td) {
    padding: 8px 0;
  }
}
</style>
